<template>
  <div class="page">
    <nav-bar title="巡检记录" border></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="handleSubmitForm"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="handleFailedForm"
          @submit="handleSubmitForm"
          :disabled="isDetail"
          :readonly="isDetail"
        >
          <van-field
            readonly
            label-class="van-cell__title_gray"
            v-model="inspectionDetail.name"
            label="点位名称"
            right-icon="arrow"
            class="van-field__right-icon-white"
          />
          <van-field
            readonly
            label-class="van-cell__title_gray"
            v-model="inspectionDetail.inspectionTime"
            label="巡查时间"
            right-icon="arrow"
            class="van-field__right-icon-white"
          />
          <!-- 第一次巡查 || 隐患已解决 -->
          <template v-if="true">
            <van-field
              required
              readonly
              clickable
              name="inspectionResultCompany"
              v-model="formParams.inspectionResultCompanyName"
              label="巡查结果"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.inspectionResultCompany"
              @click="dictOpenPopup('inspectionResultCompany')"
            />
            <template v-if="formParams.inspectionResultCompany === '1'">
              <van-field
                required
                readonly
                clickable
                name="latentDangerLevel"
                v-model="formParams.latentDangerLevelName"
                label="隐患风险级别"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.latentDangerLevel"
                @click="dictOpenPopup('latentDangerLevel')"
              />
              <van-field
                required
                readonly
                clickable
                name="plannedCompletionTime"
                v-model="formParams.plannedCompletionTime"
                label="计划完成整改时间"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.plannedCompletionTime"
                @click="dateOpenPopup('plannedCompletionTime')"
              />
              <van-field
                required
                name="correctionManager"
                v-model="formParams.correctionManager"
                label="整改负责人"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="20"
                :rules="rules.correctionManager"
              />
              <van-field
                required
                name="correctionManagerPhone"
                v-model="formParams.correctionManagerPhone"
                label="负责人联系方式"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.correctionManagerPhone"
              />
              <van-field required label="隐患排查存在问题及说明" :label-width="180" readonly :border="false" />
              <van-field
                name="latentDangerDetail"
                v-model="formParams.latentDangerDetail"
                placeholder="请输入存在的隐患问题"
                rows="5"
                autosize
                type="textarea"
                show-word-limit
                :border="false"
                input-align="left"
                class="van-field__value--textarea"
                maxlength="200"
                :rules="rules.latentDangerDetail"
              />
              <van-field
                required
                readonly
                clickable
                name="latentDangerResult"
                v-model="formParams.latentDangerResultName"
                label="隐患解决情况"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.latentDangerResult"
                @click="dictOpenPopup('latentDangerResult')"
              />
              <template v-if="formParams.latentDangerResult === '1'">
                <van-field
                  required
                  readonly
                  clickable
                  name="actualFinishTime"
                  v-model="formParams.actualFinishTime"
                  label="实际完成整改时间"
                  placeholder="请选择"
                  right-icon="arrow"
                  :rules="rules.actualFinishTime"
                  @click="dateOpenPopup('actualFinishTime')"
                />
                <van-field
                  required
                  name="acceptanceCheckManager"
                  v-model="formParams.acceptanceCheckManager"
                  label="验收人"
                  placeholder="请输入"
                  right-icon="arrow"
                  class="van-field__right-icon-white"
                  :maxlength="20"
                  :rules="rules.acceptanceCheckManager"
                />
                <van-field
                  required
                  name="acceptanceCheckManagerPhone"
                  v-model="formParams.acceptanceCheckManagerPhone"
                  label="验收人联系方式"
                  placeholder="请输入"
                  right-icon="arrow"
                  class="van-field__right-icon-white"
                  :rules="rules.acceptanceCheckManagerPhone"
                />
              </template>
            </template>
          </template>
          <div style="margin: 60px 16px" v-if="!isDetail">
            <van-row :gutter="23">
              <van-col span="12">
                <van-button block native-type="button" @click="handleClearForm">清空</van-button>
              </van-col>
              <van-col span="12">
                <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
              </van-col>
            </van-row>
          </div>
          <!--          <div style="margin: 60px 16px" v-if="isDetail && inspectionDetail.inspectionPointRecords.length < 2">-->
          <!--            <van-row :gutter="23">-->
          <!--              <van-col span="24">-->
          <!--                <van-button block native-type="button" @click="handleCheckAgain" type="info">再次巡检</van-button>-->
          <!--              </van-col>-->
          <!--            </van-row>-->
          <!--          </div>-->
          <!-- 字典项 -->
          <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
            <van-picker
              show-toolbar
              :readonly="isDetail"
              :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
              :columns="dictData[dictType]"
              value-key="description"
              @cancel="dictPopupShow = false"
              @confirm="dictOnConfirm"
              @change="dictOnChange"
            />
          </van-popup>
          <van-popup v-model="datePopupShow" round position="bottom" @close="date = new Date()">
            <van-datetime-picker
              v-model="date"
              :readonly="isDetail"
              type="date"
              title="选择年月日"
              @cancel="datePopupShow = false"
              @confirm="dateOnConfirm"
            />
          </van-popup>
        </van-form>
      </van-sticky>
    </div>
  </div>
</template>
<script>
import CampusSecurity from '@/api/campussecurity'
import SelectPopup from '@/mixins/selectPopup'
import { residentNameReg, phoneReg } from '@/libs/regexp'
import { formatTimes } from '@/libs/tool'

class FormParams {
  constructor() {
    // 网格编码
    this.gridCode = '' // 111
    this.companyCode = '' // 111
    // 巡查结果
    this.inspectionResult = '' // 111
    this.inspectionResultCompany = ''
    this.inspectionResultCompanyName = ''

    // 存在隐患
    // 风险级别
    this.latentDangerLevel = '' // 111
    this.latentDangerLevelName = '' // 111
    // 隐患排查存在问题及说明
    this.latentDangerDetail = '' // 111
    // 计划完成时间
    this.plannedCompletionTime = '' // 111
    // 整改负责人
    this.correctionManager = '' // 111
    // 整改负责人电话
    this.correctionManagerPhone = '' // 111

    // 隐患解决情况
    this.latentDangerResult = '' // 111
    this.latentDangerResultName = ''
    // 实际完成时间
    this.actualFinishTime = '' // 111
    // 整改验收负责人
    this.acceptanceCheckManager = '' // 111
    // 整改验收负责人电话
    this.acceptanceCheckManagerPhone = '' // 111
  }
}
export default {
  mixins: [SelectPopup],
  data() {
    return {
      isDetail: false,
      dictTypes: 'inspectionResultCompany,latentDangerResult,latentDangerLevel,latentDangerType',

      inspectionDetail: {
        name: '',
        inspectionTime: '',
        inspectionRecord: [],
        inspectionPointRecords: []
      },
      formParams: new FormParams(),
      rules: {
        inspectionResultCompany: [{ required: true, message: '请选择巡查结果' }],
        latentDangerLevel: [{ required: true, message: '请选择隐患风险级别' }],
        latentDangerDetail: [{ required: true, message: '请输入隐患排查存在问题及说明' }],
        plannedCompletionTime: [{ required: true, message: '请选择计划完成整改时间' }],
        correctionManager: [
          { required: true, message: '请输入整改负责人' },
          { pattern: residentNameReg, message: '请输入中文、英文和"·"' }
        ],
        correctionManagerPhone: [
          { required: true, message: '请输入联系方式' },
          { pattern: phoneReg, message: '请输入正确的联系方式' }
        ],
        latentDangerResult: [{ required: true, message: '请选择隐患解决情况' }],
        actualFinishTime: [{ required: true, message: '请选择实际完成整改时间' }],
        acceptanceCheckManager: [
          { required: true, message: '请输入验收负责人' },
          { pattern: residentNameReg, message: '请输入中文、英文和"·"' }
        ],
        acceptanceCheckManagerPhone: [
          { required: true, message: '请输入联系方式' },
          { pattern: phoneReg, message: '请输入正确的联系方式' }
        ]
      },
      buttonDisabled: false
    }
  },
  created() {
    this.getDict(this.dictTypes)
    // 有时间表示新增
    if (this.$route.query.type) {
      this.isDetail = true
      this.getDetail()
    } else {
      this.isDetail = false
      this.inspectionDetail.name = this.$route.query.inspectionPointName
      this.inspectionDetail.inspectionTime = formatTimes.formatTime(new Date())
    }
  },
  methods: {
    getDetail() {
      this.inspectionDetail.name = ''
      this.inspectionDetail.inspectionTime = ''
      this.inspectionDetail.inspectionPointRecords = []
      CampusSecurity.Api.handleDetailWithCode({
        code: this.$route.query.code,
        date: this.$route.query.inspectionTime
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          if (res.data) {
            // 0永远是最新的数据
            const fromData = data.inspectionPointRecords
            this.inspectionDetail.name = fromData.inspectionPointName
            this.inspectionDetail.inspectionTime = fromData.inspectionTime
            this.inspectionDetail.inspectionPointRecords = data.inspectionPointRecords
            Object.assign(this.formParams, fromData)
            this.formParams.inspectionResultCompanyName = fromData.inspectionResultName
            this.formParams.inspectionResultCompany = fromData.inspectionResult
          }
          // if (res.data) {
          //   this.inspectionDetail = data
          //   const inspectionRecord = this.inspectionDetail.inspectionRecord
          //   const recordLen = inspectionRecord.length
          //   // 有隐患 && 未解决
          //   if (
          //     recordLen &&
          //     inspectionRecord[recordLen - 1].inspectionResultCompany === '1' &&
          //     inspectionRecord[recordLen - 1].latentDangerResult !== '1'
          //   ) {
          //     console.log('执行')
          //     this.formParams = {
          //       ...inspectionRecord[recordLen - 1]
          //     }
          //     this.formParams.inspectionResultCompany = this.formParams.inspectionResultCompany
          //     this.formParams.latentDangerResult = ''
          //     this.formParams.latentDangerResult = ''
          //   } else {
          //     // 如果没有data数据
          //     // 取外面列表数据
          //     this.inspectionDetail.name = this.$route.query.inspectionPointName
          //   }
          // }
        }
      })
    },
    dictOnChange() {
      if (this.dictType === 'inspectionResultCompany') {
        this.formParams.latentDangerLevel = ''
        this.formParams.latentDangerLevel = ''
        this.formParams.latentDangerDetail = ''
        this.formParams.plannedCompletionTime = ''
        this.formParams.correctionManager = ''
        this.formParams.correctionManagerPhone = ''
      }
    },
    // 表单 - 校验
    handleFailedForm(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    handleSubmitForm() {
      this.formParams.gridCode = this.$route.query.gridCode
      this.formParams.inspectionPointCode = this.$route.query.inspectionPointCode
      this.formParams.inspectionResult = this.formParams.inspectionResultCompany
      this.formParams.companyCode = this.$route.query.companyCode
      this.buttonDisabled = true
      CampusSecurity.Api.save(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$toast.success('提交成功')
            this.$router.go(-1)
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    },
    // 清空form
    handleClearForm() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否清空所有内容',
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.formParams = new FormParams()
        })
    },
    // 再次巡检
    handleCheckAgain() {
      this.$toast.success('请再次巡检！')
      // 清空表单
      this.formParams = new FormParams()
      this.isDetail = false
      this.inspectionDetail.name = this.$route.query.inspectionPointName
      this.inspectionDetail.inspectionTime = formatTimes.formatTime(new Date())
    }
  }
}
</script>
